/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cenluan.photo;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletInputStream;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.cenluan.common.Const;
import com.cenluan.common.OssManager;
import com.cenluan.ext.jfinal.PkController;
import com.cenluan.gallery.Gallery;
import com.cenluan.gallery.member.GalleryMember;
import com.cenluan.kit.UUIDKit;
import com.cenluan.login.ClearLoginInterceptor;
import com.cenluan.user.User;
import com.jfinal.plugin.activerecord.Page;

/**
 * 照片
 * 
 * @author peak
 * 
 */
public class PhotoController extends PkController {
	/**
	 * 相册的相片列表
	 */
	@ClearLoginInterceptor
	public void index() {
		Gallery gallery = Gallery.dao.findById(getPara());
		if (!Gallery.STATE_ACTIVE.equals(gallery.getStr("state"))) {
			renderError(404);
			return;
		}

		Page<Photo> page = Photo.dao.page(getPn(), 24, getPara(),
				getParaToInt("order", 0));
		setAttr("gallery", gallery);
		setAttr("page", page);
		setPageLink(page);
		keepPara();
	}

	/**
	 * 展示
	 */
	public void show() {
		Photo photo = Photo.dao.findById(getPara());
		if (photo == null) {
			renderError(404);
			return;
		}
		Gallery gallery = photo.getGallery();
		if (!Gallery.STATE_ACTIVE.equals(gallery.getStr("state"))) {
			renderError(404);
			return;
		}
		User user = getSessionAttr(Const.SESSION_USER);
		if (!photo.hasViewed(user.getStr("id"))) {
			photo.addView(user.getStr("id"));
		}

		List<String> idList = Photo.dao.getIdList(gallery.getStr("id"),
				getParaToInt("order", 0));
		int index = idList.indexOf(photo.getStr("id"));
		setAttr("index", index + 1);// 程序里是从0开始的，人们的习惯是从1开始
		setAttr("count", idList.size());
		if (index < idList.size() - 1) {
			setAttr("next", idList.get(index + 1));
		}
		if (index > 0) {
			setAttr("previous", idList.get(index - 1));
		}
		setAttr("photo", photo);
		setAttr("gallery", gallery);
		setAttr("galleryCreater",
				user.getStr("id").equals(gallery.getStr("createrId")));
		setAttr("creater", user.getStr("id").equals(photo.getStr("createrId")));
		setAttr("favorited", photo.hasFavorited(user.getStr("id")));
		keepPara();

	}

	/**
	 * 添加，去上传页面
	 */
	public void add() {
		Gallery gallery = Gallery.dao.findById(getPara());
		User user = getSessionAttr(Const.SESSION_USER);
		GalleryMember member = GalleryMember.dao.findBygalleryIdAndUserId(
				gallery.getStr("id"), user.getStr("id"));
		if (!user.getStr("id").equals(gallery.getStr("createrId"))
				&& (member == null || !member.getBoolean("active"))) {
			renderError(403);
			return;
		}
		setAttr("gallery", gallery);
	}

	/**
	 * 上传保存
	 * 
	 * @throws IOException
	 */
	public void save() throws IOException {
		Gallery gallery = Gallery.dao.findById(getPara());
		User user = getSessionAttr(Const.SESSION_USER);
		GalleryMember member = GalleryMember.dao.findBygalleryIdAndUserId(
				gallery.getStr("id"), user.getStr("id"));
		if (!user.getStr("id").equals(gallery.getStr("createrId"))
				&& (member == null || !member.getBoolean("active"))) {
			renderError(403);
			return;
		}
		Photo photo = new Photo();
		photo.set("id", UUIDKit.generateUUID());
		// 上传到阿里云存储
		String key = UUIDKit.generateUUID() + ".jpg";
		ServletInputStream in = getRequest().getInputStream();
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentLength(getRequest().getContentLength());
		OssManager.saveImage(in, metadata, key);
		photo.set("key", key);
		photo.set("createrId", user.getStr("id"));
		photo.set("createTime", new Date());
		photo.set("galleryId", gallery.getStr("id"));
		photo.save();
		renderNull();
	}

	/**
	 * 删除，有三种人可以删除照片：<br>
	 * 1.照片的创建者<br>
	 * 2.相册的创建者<br>
	 * 3.网站管理员
	 */
	public void delete() {
		User user = getSessionAttr(Const.SESSION_USER);
		Photo photo = Photo.dao.findById(getPara());
		Gallery gallery = photo.getGallery();
		if (!User.ROLE_ADMIN.equals(user.getStr("role"))
				&& !gallery.getStr("createrId").equals(user.getStr("id"))
				&& !photo.getStr("createrId").equals(user.getStr("id"))) {
			renderError(403);
			return;
		}
		// 如果这张照片是相册的封面，将相册封面置空
		if (photo.get("id").equals(gallery.getStr("coverId"))) {
			gallery.set("coverId", null);
			gallery.keep("id", "coverId").update();
		}
		photo.delete();
		setAttr("ok", true);
		renderJson();
	}

	/**
	 * 全屏
	 */
	public void fullScreen() {
		Photo photo = Photo.dao.findById(getPara());
		setAttr("photo", photo);
	}
}
